﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Forms;
using System.Threading;
using PrelucrareParametrii;

namespace HelpNetwork
{
    
    public partial class Principal : Form
    {
        //delegati pentru Invoke (Reflection)
        private delegate void SetTextCallback(string text);
        private delegate void UpdateParameterCallback();

        public bool iesire = false;
        public bool serialConectat = false;
        public bool mesajeStareAscunse = true;

        public struct ActiveAlarms{
            public bool alarmaGaz;
            public bool alarmaLumina;
            public bool alarmaUmiditate;
            public bool alarmaRFID;
            public bool alarmaTensiune;
        };

        public static ActiveAlarms appAlarms;
        public static Principal mainForm;
        public static ConfigurareSenzori configSenzoriInstance;
        public static ConfigAplicatie configAplicatieInstance;
        public static String serialRecv;
        
        public Thread mySerialThread;
        public Thread mySocketThread;
        public static Thread mainThread;
        
        public Parametrii appParam = new Parametrii();

        public static bool seGenereazaAutomat = false;

        private int timerCounter = 0;
        private bool pauzaCaptura = false;
        private bool remoteActive = false;

        System.IO.StreamReader fileToPrint;
        System.Drawing.Font printFont;

        private void initAlarms()
        {

            appAlarms.alarmaGaz = false;
            appAlarms.alarmaLumina = false;
            appAlarms.alarmaUmiditate = false;
            appAlarms.alarmaRFID = false;
            appAlarms.alarmaTensiune = true;
        }

        public Principal()
        {
            InitializeComponent();
        }
        private void soundThread()
        {
            System.Media.SoundPlayer myPlayer = new System.Media.SoundPlayer();
            myPlayer.SoundLocation = @String.Concat(Directory.GetCurrentDirectory(),"\\alarma.wav");
            myPlayer.Play();

        }
        public void updateAlarme()
        {
            appAlarms.alarmaLumina = this.appParam.parametriiCurenti.lumina == true ? true : false;
            appAlarms.alarmaGaz = this.appParam.parametriiCurenti.gaz == true ? true : false;
            appAlarms.alarmaRFID = this.appParam.parametriiCurenti.RFID == true ? true : false;
            appAlarms.alarmaTensiune = this.appParam.parametriiCurenti.tensiuneRetea == true ? false : true;
            appAlarms.alarmaUmiditate = this.appParam.parametriiCurenti.umiditate == true ? true : false;
            if (appAlarms.alarmaGaz == true)
            {
                if (appAlarms.alarmaUmiditate == true)
                    lbAlarmeActive.Text = "Gaz detectat, umiditate mare!";
                else
                    lbAlarmeActive.Text = "Gaz detectat!";
                lbAlarmeActive.Visible = true;
            }
            else
                if (appAlarms.alarmaUmiditate == true)
                {
                    lbAlarmeActive.Text = "Umiditate mare!";
                }
                else
                    lbAlarmeActive.Visible = false;
            if (appAlarms.alarmaGaz == true || appAlarms.alarmaUmiditate == true)
            {
                try
                {
                    Thread mySoundThread = new Thread(new ThreadStart(soundThread));
                    mySoundThread.Start();
                }
                catch (Exception)
                { }
            }

        }
        public void inserareMesajStare(String mesaj)
        {
            serialRecv = mesaj;
            if (this.txtMesajeStare.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(setText);
                this.Invoke(d, new object[] { mesaj});
            }
            else
            {
                 this.txtMesajeStare.AppendText(mesaj);
            }
            if (pauzaCaptura == false)
                updateParameters(mesaj);
        }
        public void inserareMesaj(String mesaj)
        {
            if (this.txtMesajeStare.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(setText);
                this.Invoke(d, new object[] { mesaj });
            }
            else
            {
                this.txtMesajeStare.AppendText(mesaj);
            }
        }
        public void updateParameters(String mesaj)
        {
            try
            {
                int myIndex = -1, val, inundatie;
                byte[] buf = new byte[10];
                byte counter = 0;
                do
                {
                    myIndex = mesaj.IndexOf(' ');
                    buf[counter] = Byte.Parse(mesaj.Substring(0, myIndex));
                    counter++;
                    mesaj = mesaj.Substring(myIndex+1);
                }
                while (counter < 7) ;
                val = ((int)(buf[1]) << 8) + buf[0];
                int tempAmbient = (int)PrelucrareParametrii.PrelucrareParametrii.tempTI(10, val);
                appParam.parametriiCurenti.tempAmbientala = (byte)(tempAmbient);
                val = ((int)(buf[3]) << 8) + buf[2];
                appParam.parametriiCurenti.tempCorp = (byte)(PrelucrareParametrii.PrelucrareParametrii.tempSensirion(14,val));
                appParam.parametriiCurenti.tempCorp += 8;
                val = ((int)(buf[5]) << 8) + buf[4];
                inundatie = (int)(PrelucrareParametrii.PrelucrareParametrii.calcUmiditate(12,val,appParam.parametriiCurenti.tempCorp - 10));
                appParam.parametriiCurenti.umiditate = (inundatie > 120) ? true : false;
                val = ((int)(buf[7]) << 8) + buf[6];
                appParam.parametriiCurenti.lumina = PrelucrareParametrii.PrelucrareParametrii.lumina(val);


            }
            catch (Exception e)
            {
            }

            if (Principal.seGenereazaAutomat == true)
                configSenzoriInstance.makeAutoParameters();
            UpdateParameterCallback upc = new UpdateParameterCallback(updateParametriiTextBox);
            this.Invoke(upc);
            
        }


        private void setText(String txt)
        {
            txtMesajeStare.WordWrap = true;
            this.txtMesajeStare.AppendText(txt+"\r\n");          
        }

        private void lbEKG_MouseHover(object sender, EventArgs e)
        {
            System.Windows.Forms.ToolTip toolTip = new System.Windows.Forms.ToolTip();

            toolTip.AutoPopDelay = 5000;
            toolTip.InitialDelay = 1000;
            toolTip.ReshowDelay = 500;
            toolTip.ShowAlways = true;

            toolTip.SetToolTip(lbEKG,"Electrocardiograma (mV)");
        }

        private void lbHTA_MouseHover(object sender, EventArgs e)
        {
            System.Windows.Forms.ToolTip toolTip = new System.Windows.Forms.ToolTip();

            toolTip.AutoPopDelay = 5000;
            toolTip.InitialDelay = 1000;
            toolTip.ReshowDelay = 500;
            toolTip.ShowAlways = true;

            toolTip.SetToolTip(lbHTA, "Hipertensiune arteriala (mmHg)");
        }

        private void label9_MouseHover(object sender, EventArgs e)
        {
            System.Windows.Forms.ToolTip toolTip = new System.Windows.Forms.ToolTip();

            toolTip.AutoPopDelay = 5000;
            toolTip.InitialDelay = 1000;
            toolTip.ReshowDelay = 500;
            toolTip.ShowAlways = true;

            toolTip.SetToolTip(lbPuls, "Frecventa Puls (Bpm)");
        }

        private void lbTemperatura_MouseHover(object sender, EventArgs e)
        {
            System.Windows.Forms.ToolTip toolTip = new System.Windows.Forms.ToolTip();

            toolTip.AutoPopDelay = 5000;
            toolTip.InitialDelay = 1000;
            toolTip.ReshowDelay = 500;
            toolTip.ShowAlways = true;

            toolTip.SetToolTip(lbTemperaturaCorp, "Temperatura corporala (°C)");
        }

        private void lbGreutate_MouseHover(object sender, EventArgs e)
        {
            System.Windows.Forms.ToolTip toolTip = new System.Windows.Forms.ToolTip();

            toolTip.AutoPopDelay = 5000;
            toolTip.InitialDelay = 1000;
            toolTip.ReshowDelay = 500;
            toolTip.ShowAlways = true;

            toolTip.SetToolTip(lbGreutate, "Greutate corporala (kg)");
        }


        private void lbFrecventaRespiratorie_MouseHover(object sender, EventArgs e)
        {
            System.Windows.Forms.ToolTip toolTip = new System.Windows.Forms.ToolTip();

            toolTip.AutoPopDelay = 5000;
            toolTip.InitialDelay = 1000;
            toolTip.ReshowDelay = 500;
            toolTip.ShowAlways = true;

            toolTip.SetToolTip(lbFrecventaRespiratorie, "Ritmul respiratiei (resp. per min.)");
        }

        private void lbLumina_MouseHover(object sender, EventArgs e)
        {
            System.Windows.Forms.ToolTip toolTip = new System.Windows.Forms.ToolTip();

            toolTip.AutoPopDelay = 5000;
            toolTip.InitialDelay = 1000;
            toolTip.ReshowDelay = 500;
            toolTip.ShowAlways = true;

            toolTip.SetToolTip(lbLumina, "Senzor lumina ambientala (da/nu)");
        }

        private void lbTemperaturaAmbientala_MouseHover(object sender, EventArgs e)
        {
            System.Windows.Forms.ToolTip toolTip = new System.Windows.Forms.ToolTip();

            toolTip.AutoPopDelay = 5000;
            toolTip.InitialDelay = 1000;
            toolTip.ReshowDelay = 500;
            toolTip.ShowAlways = true;

            toolTip.SetToolTip(lbTemperaturaAmbientala, "Temperatura ambientala (°C)");
        }

        private void lbGaz_MouseHover(object sender, EventArgs e)
        {
            System.Windows.Forms.ToolTip toolTip = new System.Windows.Forms.ToolTip();

            toolTip.AutoPopDelay = 5000;
            toolTip.InitialDelay = 1000;
            toolTip.ReshowDelay = 500;
            toolTip.ShowAlways = true;

            toolTip.SetToolTip(lbGaz, "Senzor de gaz metan si/sau monoxid de carbon");
        }

        private void lbUmiditate_MouseHover(object sender, EventArgs e)
        {
            System.Windows.Forms.ToolTip toolTip = new System.Windows.Forms.ToolTip();

            toolTip.AutoPopDelay = 5000;
            toolTip.InitialDelay = 1000;
            toolTip.ReshowDelay = 500;
            toolTip.ShowAlways = true;

            toolTip.SetToolTip(lbUmiditate, "Senzor de umiditate (inundatie)");
        }

        private void lbRFID_MouseHover(object sender, EventArgs e)
        {
            System.Windows.Forms.ToolTip toolTip = new System.Windows.Forms.ToolTip();

            toolTip.AutoPopDelay = 5000;
            toolTip.InitialDelay = 1000;
            toolTip.ReshowDelay = 500;
            toolTip.ShowAlways = true;

            toolTip.SetToolTip(lbRFID, "Sesizare prezenta in camera");
        }

        private void lbTensiuneRetea_MouseHover(object sender, EventArgs e)
        {
            System.Windows.Forms.ToolTip toolTip = new System.Windows.Forms.ToolTip();

            toolTip.AutoPopDelay = 5000;
            toolTip.InitialDelay = 1000;
            toolTip.ReshowDelay = 500;
            toolTip.ShowAlways = true;

            toolTip.SetToolTip(lbTensiuneRetea, "Sesizare existenta tensiune retea electrica ");
        }

        private void lbGlicemie_MouseHover(object sender, EventArgs e)
        {
            System.Windows.Forms.ToolTip toolTip = new System.Windows.Forms.ToolTip();

            toolTip.AutoPopDelay = 5000;
            toolTip.InitialDelay = 1000;
            toolTip.ReshowDelay = 500;
            toolTip.ShowAlways = true;

            toolTip.SetToolTip(lbGlicemie, "Valoarea masurata a glicemiei, transmisa la comanda pacientului");
        }
        private void citesteSenzori(String mesaj)
        {
            Byte[] dateCitite = new Byte[9];
            Byte contorDate = 0;
            String s = mesaj;
            int spaceIndex;
            do{
                spaceIndex = mesaj.IndexOf(' ');
                s = mesaj.Substring(0, spaceIndex);
                dateCitite[contorDate] = Byte.Parse(s);
                contorDate++;
                mesaj = mesaj.Substring(spaceIndex, mesaj.Length);
                
            }
            while (spaceIndex <= mesaj.Length);

        }
        private void updateParametriiTextBox()
        {
            //lbEKGVal.Text = appParam.parametriiCurenti.EKG.ToString();
            lbHTASystolicVal.Text = appParam.parametriiCurenti.HTA.Sistolic.ToString();
            lbHTADiastolicVal.Text = appParam.parametriiCurenti.HTA.Diastolic.ToString();
            lbPulsVal.Text = appParam.parametriiCurenti.puls.ToString();
            lbTemperaturaCorpVal.Text = appParam.parametriiCurenti.tempCorp.ToString();
            lbTemperaturaAmbientalaVal.Text = appParam.parametriiCurenti.tempAmbientala.ToString();
            lbGreutateVal.Text = appParam.parametriiCurenti.greutate.ToString();
            lbGlicemieVal.Text = appParam.parametriiCurenti.glicemie.ToString();
            lbFrecventaRespiratorieVal.Text = appParam.parametriiCurenti.frecvResp.ToString();

            if (appParam.parametriiCurenti.lumina == true)
                lbLuminaVal.Text = "aprinsa";
            else
                lbLuminaVal.Text = "stinsa";
            lbTemperaturaCorpVal.Text = appParam.parametriiCurenti.tempCorp.ToString();
            if ( appParam.parametriiCurenti.gaz == true ) 
             lbGazVal.Text = "da" ;
            else
                lbGazVal.Text = "nu";
            if (appParam.parametriiCurenti.umiditate == true)
                lbUmiditateVal.Text = "da";
            else
                lbUmiditateVal.Text = "nu";
            if (appParam.parametriiCurenti.RFID == true)
                lbRFIDVal.Text = "da";
            else
                lbRFIDVal.Text = "nu";
            if (appParam.parametriiCurenti.tensiuneRetea == true)
                lbTensiuneReteaVal.Text = "da";
            else
                lbTensiuneReteaVal.Text = "nu";
        }
        private void btnConfigSenzori_Click(object sender, EventArgs e)
        {
          configSenzoriInstance = new ConfigurareSenzori();
          configSenzoriInstance.Show();      
          this.Enabled = false;
        }
        private static void SerialThread()
        {
            try
            {
                SerialDump mySerialDump = new SerialDump();

                while (Principal.mainForm.iesire != true)
                    mySerialDump.Run();
                Principal.mainForm.iesire = true;
                //introdu buton reconectare
                if (mySerialDump.serialIsConnected == true) mySerialDump.Stop();
                Principal.mainForm.mySerialThread.Abort();
            }
            catch (ApplicationException)
            {
            }
            catch (ThreadAbortException)
            {

            }
            catch (Exception e)
            {
                Principal.mainForm.inserareMesajStare(String.Concat("Eroare de comunicatie: {0}", e.ToString()));

            }
            

        }
        public void afisareMesajeStare()
        {
            grpMesajeStare.Visible = true;
            mesajeStareAscunse = false;
            txtMesajeStare.Visible = true;
        }
        public void ascundeMesajeStare()
        {
            txtMesajeStare.Visible = false;
            mesajeStareAscunse = true;
            grpMesajeStare.Visible = false;
        } 
        private void adaugaDateSalvate(ref Param paramToInsert)
        {
            string[] myItems = new string[] { paramToInsert.HTA.Diastolic.ToString(),
            paramToInsert.HTA.Sistolic.ToString(), paramToInsert.puls.ToString(), paramToInsert.tempCorp.ToString(), paramToInsert.greutate.ToString(),
            paramToInsert.glicemie.ToString(), paramToInsert.frecvResp.ToString(), paramToInsert.tempAmbientala.ToString(), paramToInsert.lumina.ToString(),
            paramToInsert.gaz.ToString(), paramToInsert.umiditate.ToString(), paramToInsert.RFID.ToString(), paramToInsert.tensiuneRetea.ToString()};
            lvwDateLocale.Items.Add(paramToInsert.dataOraPreluarii.ToString());
            for (int i = 0; i <= 12; i++)
            {
                lvwDateLocale.Items[lvwDateLocale.Items.Count - 1].SubItems.Add(new ListViewItem.ListViewSubItem(lvwDateLocale.Items[lvwDateLocale.Items.Count - 1],myItems[i]));
            }

        }

        private void Principal_Load(object sender, EventArgs e)
        {
            initAlarms();
            citesteDateSalvate();
            appParam.parametriiCurenti = new Param();
            mySerialThread = new System.Threading.Thread(new System.Threading.ThreadStart(SerialThread));
            mySerialThread.Start();
            timer1.Interval = 500;
            timer1.Start();
        }
        private void txtMesajeStare_TextChanged(object sender, EventArgs e)
        {
            stareCurenta.Text = txtMesajeStare.Text.Substring(txtMesajeStare.GetFirstCharIndexOfCurrentLine());

        }

        private void Principal_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (lvwDateLocale.Items.Count !=0)
                salveazaDate();
            iesire = true;

        }

        private void btnConfigDispecerat_Click(object sender, EventArgs e)
        {
            configAplicatieInstance = new ConfigAplicatie();
            configAplicatieInstance.Show();
            this.Enabled = false;
        }

        private void btnPauzaCaptura_Click(object sender, EventArgs e)
        {
            pauzaCaptura = !pauzaCaptura;
            if (pauzaCaptura == true)
                btnPauzaCaptura.Text = "Reluare captura";
            else
                btnPauzaCaptura.Text = "Pauza captura";
        }

        private void btnStergeMesajeStare_Click(object sender, EventArgs e)
        {
            txtMesajeStare.Text = null;
        }

        private void btnAjutor_Click(object sender, EventArgs e)
        {

            String myURL = String.Concat(Directory.GetCurrentDirectory(), "\\Help\\index.htm");
            try
            {
                System.Diagnostics.Process.Start(myURL);
            }
            catch (Exception helpException)
            {
                MessageBox.Show(String.Concat("Nu s-a gasit fisierul de ajutor la calea ", myURL), "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void btnEKG_Click(object sender, EventArgs e)
        {
            //inseram form nou cu EKG
            new EKG().Show();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {

            if (iesire == true)
            {
           //     this.btnConfigParametrii.Enabled = false;
       //         this.btnSalvareDate.Enabled = false;
         //       this.btnPauzaCaptura.Enabled = false;
                //mutare ce-i mai jos in else la release si uncomment mai sus!
                timerCounter++;
                if (timerCounter == 5)
                    updateAlarme();
                if (timerCounter == 50)
                {
                    timerCounter = 0;
                    WebComm.sendMessage(appAlarms, Principal.mainForm.appParam.adresaDispecerat);
            }
            else
            {

                }

            }

                
        }

        private void btnSalvareDate_Click(object sender, EventArgs e)
        {
            appParam.parametriiCurenti.dataOraPreluarii = DateTime.Now;
            adaugaDateSalvate(ref appParam.parametriiCurenti);

           
        }

        private void salveazaDate()
        {
            try
            {
                DataTable dt = new DataTable("DateSalvate");
                foreach (ColumnHeader col in lvwDateLocale.Columns)
                {
                    dt.Columns.Add(col.Text, typeof(string));
                }
                object[] vals = new object[lvwDateLocale.Columns.Count];
                foreach (ListViewItem item in lvwDateLocale.Items)
                {
                    ListViewItem.ListViewSubItemCollection items =
                    item.SubItems;
                    for (int i = 0; i < vals.Length; i++)
                    {
                        vals[i] = items[i].Text;
                    }
                    dt.Rows.Add(vals);
                }
                dt.WriteXml(@String.Concat(Directory.GetCurrentDirectory(), "\\DateSalvate.xml"));
            }
            catch (Exception)
            {
                MessageBox.Show("Eroare la salvarea datelor.", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void citesteDateSalvate()
        {
            try
            {

                DataSet mySet = new DataSet();
                mySet.ReadXml(@String.Concat(Directory.GetCurrentDirectory(), "\\DateSalvate.xml"));
                DataTable myTable = mySet.Tables[0];

                object[] vals = new object[lvwDateLocale.Columns.Count];

                foreach (DataRow dr in myTable.Rows)
                {
                    ListViewItem lv = new ListViewItem();
                    for (int i = 0; i < lvwDateLocale.Columns.Count; i++)
                    {
                        vals[i] = dr.ItemArray[i].ToString();

                    }
                    lv.Text = vals[0].ToString();
                    for (int i = 1; i < lvwDateLocale.Columns.Count; i++)
                    {
                        lv.SubItems.Add(new ListViewItem.ListViewSubItem(lv, vals[i].ToString()));
                    }
                    lvwDateLocale.Items.Add(lv);

                }
            }
            catch (Exception)
            { }
        }

        private void btnStergereDate_Click(object sender, EventArgs e)
        {
            try{
                File.Delete(String.Concat(Directory.GetCurrentDirectory(), "\\DateSalvate.xml"));
            }
            catch(Exception)
            {}
            lvwDateLocale.Items.Clear();
        }

        private void btnStergeDateSelectate_Click(object sender, EventArgs e)
        {
            try
            {
                lvwDateLocale.Items.Remove(lvwDateLocale.SelectedItems[0]);
            }
            catch (Exception)
            {
                MessageBox.Show("Nu ati selectat niciun set de date. Va rugam selectati un set de date!", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void btnMobil_Click(object sender, EventArgs e)
        {
            remoteActive = !remoteActive;
            btnMobil.Text = remoteActive == true? "Dezactivare \r\n conex. mobila": "Permite conex.\r\n mobila";
            if (remoteActive == true)
            {
                mySocketThread = new Thread(new ThreadStart(SocketServer.createNewServer));
                mySocketThread.Start();
            }
            else
            {
                //SocketServer.keepAlive = false;
            }

        }

        private void btnPrintare_Click(object sender, EventArgs e)
        {
            string printPath = Directory.GetCurrentDirectory() + @"\tempPrint.tmp";

            StreamWriter fisier = new StreamWriter(printPath, false);
            fisier.WriteLine("HelpNetwork Client"); 
            fisier.WriteLine("(c) 2011 Biosync. Toate drepturile rezervate. ");
            fisier.WriteLine(Environment.NewLine);
            fisier.WriteLine("HTA: Diastolic - " + appParam.parametriiCurenti.HTA.Diastolic + ", Sistolic - "+appParam.parametriiCurenti.HTA.Sistolic);
            fisier.WriteLine("Puls: " + appParam.parametriiCurenti.puls);
            fisier.WriteLine("Temperatura Corp: " + appParam.parametriiCurenti.tempCorp);
            fisier.WriteLine("Greutate: " + appParam.parametriiCurenti.greutate);
            fisier.WriteLine("Glicemie: " + appParam.parametriiCurenti.glicemie);
            fisier.WriteLine("Frecventa respiratorie: " + appParam.parametriiCurenti.frecvResp);
            if (appParam.parametriiCurenti.lumina == true)
                fisier.WriteLine("Lumina aprinsa");
            else
                fisier.WriteLine("Lumina stinsa");
            fisier.WriteLine("Temperatura ambientala: " + appParam.parametriiCurenti.tempAmbientala);
            if (appParam.parametriiCurenti.gaz == true)
                fisier.WriteLine("Scurgere de gaz detectata!");
            else
                fisier.WriteLine("Nu a fost detectata o scurgere de gaz.");

            if (appParam.parametriiCurenti.umiditate == true)
                fisier.WriteLine("Umiditate f. mare detectata!");
            else
                fisier.WriteLine("Nu a fost detectata nicio anomalie de umiditate.");

            if (appParam.parametriiCurenti.RFID == true)
                fisier.WriteLine("Pacientul avea cartela RFID in incapere.");
            else
                fisier.WriteLine("Nu a fost detectata cartela RFID.");

            if (appParam.parametriiCurenti.tensiuneRetea == true)
                fisier.WriteLine("Reteaua electrica functioneaza.");
            else
                fisier.WriteLine("Lipsa curent electric, sistemul functioneaza pe baterii.");


            fisier.Close();
            fileToPrint = new System.IO.StreamReader(printPath);
            printFont = new System.Drawing.Font("Arial", 12);
            printDocument1.Print();
            fileToPrint.Close();
        }

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            float yPos = 0f;
            int count = 0;
            float leftMargin = e.MarginBounds.Left;
            float topMargin = e.MarginBounds.Top;
            string line = null;
            float linesPerPage = e.MarginBounds.Height / printFont.GetHeight(e.Graphics);
            while (count < linesPerPage)
            {
                line = fileToPrint.ReadLine();
                if (line == null)
                {
                    break;
                }
                yPos = topMargin + count * printFont.GetHeight(e.Graphics);
                e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
                count++;
            }
            if (line != null)
            {
                e.HasMorePages = true;
            }
        }
 
    }
}
